export default class WebSocketClient {  
    constructor(url, protocols = []) {  
      this.url = url;  
      this.protocols = protocols;  
      this.ws = null;   
      this.initWebSocket();  
    }  
    
    initWebSocket() {  
      this.ws = new WebSocket(this.url, this.protocols);  
      this.readyState = WebSocket.CONNECTING;  
    
      this.ws.onopen = () => {  
        this.readyState = WebSocket.OPEN;  
        this.reconnectAttempts = 0;  
        this.onOpen();  
      };  
    
      this.ws.onmessage = (event) => {  
        this.onMessage(event);  
      };  
    
      this.ws.onclose = () => {  
        this.readyState = WebSocket.CLOSED;  
        this.onClose();  
        this.reconnect();  
      };  
    
      this.ws.onerror = (error) => {  
        this.onError(error);  
      };  
    }  
    
    send(data) {  
      if (this.readyState === WebSocket.OPEN) {  
        this.ws.send(data);  
      } else {  
        console.log("WebSocket is not open. Ready state:", this.readyState);  
      }  
    }  
    
    close() {  
      this.ws.close();  
      this.readyState = WebSocket.CLOSING;  
    }  
    
    reconnect() {  
      if (this.reconnectAttempts < this.maxReconnectAttempts) {  
        this.reconnectAttempts++;  
        setTimeout(() => this.initWebSocket(), this.reconnectInterval);  
      } else {  
        console.log("Max reconnect attempts reached");  
      }  
    }  
    
    // 事件处理程序的占位符，供子类或实例重写  
    onOpen() {}  
    onMessage(event) {}  
    onClose() {}  
    onError(error) {}  
  }